#include "GfxDriver/WGL/WGLDepthBuffer.h"

#include "GfxDriver/GfxDriver.h"

#include <cstdlib>

namespace Orca {

	//--------------------------------------------------------------------------
	WGLDepthBuffer* WGLDepthBuffer::create(
		 GfxDriver *gfxDriver
		,uint32 width
		,uint32 height
		,uint32 depthBits
		,uint32 stencilBits) {

		WGLDepthBuffer *depthBuf = new WGLDepthBuffer;

		if( !depthBuf->_init(gfxDriver, width, height, depthBits, stencilBits) ) {

			delete depthBuf;
			return NULL;
		}

		return depthBuf;
	}

	//--------------------------------------------------------------------------
	bool WGLDepthBuffer::_init(
		 GfxDriver *gfxDriver
		,uint32 width
		,uint32 height
		,uint32 depthBits
		,uint32 stencilBits) {

		mGfxDriver = gfxDriver;
		mW = width;
		mH = height;

		mGfxDriver->resetErrors();

		glGenRenderbuffersEXT(1, &mGLHandle);

		glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, mGLHandle);

		glRenderbufferStorageEXT(
			GL_RENDERBUFFER_EXT,
			GL_DEPTH_COMPONENT24,
			(GLsizei)mW,
			(GLsizei)mH);

		glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);

		if( GL_NO_ERROR != glGetError() )
			return false;

		return true;
	}

	//--------------------------------------------------------------------------
	WGLDepthBuffer::WGLDepthBuffer()
		: mGfxDriver(NULL) 
		, mW(0)
		, mH(0)
		, mGLHandle(0) {

	}
	
	//--------------------------------------------------------------------------
	WGLDepthBuffer::~WGLDepthBuffer() {
	
		if(mGLHandle)
			glDeleteRenderbuffersEXT(1, &mGLHandle);
	}

	//--------------------------------------------------------------------------
	uint32 WGLDepthBuffer::getWidth() {

		return mW;
	}

	//--------------------------------------------------------------------------
	uint32 WGLDepthBuffer::getHeight() {

		return mH;
	}

	//--------------------------------------------------------------------------
	unsigned int WGLDepthBuffer::getAPIHandle() {

		return mGLHandle;
	}

	//--------------------------------------------------------------------------
}